package vn.vfriends.vcms.admin.service.impl;

import java.util.List;
import java.util.Set;
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceUnit;
import javax.persistence.Query;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.transaction.Status;
import javax.transaction.UserTransaction;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import vn.vfriends.vcms.admin.model.Category;
import vn.vfriends.vcms.admin.model.Item;
import vn.vfriends.vcms.admin.service.ItemService;
import vn.vfriends.vcms.admin.service.impl.exceptions.NonexistentEntityException;
import vn.vfriends.vcms.admin.service.impl.exceptions.RollbackFailureException;
import vn.vfriends.vcms.admin.service.impl.exceptions.ViolationException;

/**
 *
 * @author tuan@vfriends.vn
 */
public class ItemJpaController implements ItemService {

    @Resource
    private UserTransaction utx = null;
    @PersistenceUnit(unitName = "vcmsPU")
    private EntityManagerFactory emf = null;
    @Inject
    private Validator validator;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    @Override
    public void createItem(Item item) throws RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            Set<ConstraintViolation<Item>> violations = this.validator.validate(item);
            if (violations.size() > 0) {
                ViolationException exception = new ViolationException(violations);
                throw exception;
            }
            
            utx.begin();
            em = getEntityManager();
            Category category = item.getCategory();
            if (category != null) {
                category = em.getReference(category.getClass(), category.getId());
                item.setCategory(category);
            }
            em.persist(item);
            if (category != null) {
                category.getItems().add(item);
                category = em.merge(category);
            }
            utx.commit();
        } catch (ViolationException ve) {
            throw ve;
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void editItem(Item item) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            Set<ConstraintViolation<Item>> violations = this.validator.validate(item);
            if (violations.size() > 0) {
                ViolationException exception = new ViolationException(violations);
                throw exception;
            }
            
            utx.begin();
            em = getEntityManager();
            Item persistentItem = em.find(Item.class, item.getId());
            Category oldCategory = persistentItem.getCategory();
            Category newCategory = item.getCategory();
            if (newCategory != null) {
                newCategory = em.getReference(newCategory.getClass(), newCategory.getId());
                item.setCategory(newCategory);
            }
            item = em.merge(item);
            if (oldCategory != null && !oldCategory.equals(newCategory)) {
                oldCategory.getItems().remove(item);
                oldCategory = em.merge(oldCategory);
            }
            if (newCategory != null && !newCategory.equals(oldCategory)) {
                newCategory.getItems().add(item);
                newCategory = em.merge(newCategory);
            }
            utx.commit();
        } catch (ViolationException ve) {
            throw ve;
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Long id = item.getId();
                if (findItem(id) == null) {
                    throw new NonexistentEntityException("The item with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public void destroyItem(Long id) throws NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Item item;
            try {
                item = em.getReference(Item.class, id);
                item.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The item with id " + id + " no longer exists.", enfe);
            }
            Category category = item.getCategory();
            if (category != null) {
                category.getItems().remove(item);
                category = em.merge(category);
            }
            em.remove(item);
            utx.commit();
        } catch (Exception ex) {
            try {
                if (utx.getStatus() == Status.STATUS_ACTIVE) {
                    utx.rollback();
                }
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    @Override
    public List<Item> findItems() {
        return findItems(true, -1, -1);
    }

    @Override
    public List<Item> findItems(int maxResults, int firstResult) {
        return findItems(false, maxResults, firstResult);
    }

    private List<Item> findItems(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Item.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    @Override
    public Item findItem(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Item.class, id);
        } finally {
            em.close();
        }
    }

    @Override
    public int getItemCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Item> rt = cq.from(Item.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
